<?php
// 注册处理页面
session_start();
//header('location: '.$_SERVER['HTTP_REFERER']);
if(isset($_POST["hidden"])&&$_POST["hidden"]=="hidden"){
    $user=trim($_POST["username"]);
    $pwd =md5(trim($_POST["userpwd"]));
    $pwd_confirm=md5(trim($_POST["confirm"]));
    $code=trim($_POST["code"]);
    if($user=="" || $pwd=="" || $pwd_confirm==""|| $code==""){
        echo "<script>alert('请确认信息完整');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
    }elseif(strtolower($code)!=strtolower($_SESSION['code'])){
        echo "<script>alert('验证码错误');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
    }else{
        if($pwd==$pwd_confirm){
            // 写入数据库
            $conn= mysqli_connect("localhost","root","Immo.cn8");
            if(mysqli_errno($conn)){
                echo mysqli_errno($conn);
                exit;
            }
            mysqli_select_db($conn,"userdb");
            mysqli_set_charset($conn,"utf8");
            $sql="select username from user where username='$user'";
            $res=mysqli_query($conn,$sql);
            $num=mysqli_num_rows($res);
            if($num){
                echo "<script>alert('用户名已存在');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
            }else{
                $ip=ip2long($_SERVER['REMOTE_ADDR']);
                $time=time();
                $sql_ins="insert into `user` (`username`,`userpwd`,`createtime`,`createip`) VALUES('$user','$pwd','$time','$ip')";
                $res_ins=mysqli_query($conn,$sql_ins);
                if($res_ins){
                    echo "<script>alert('注册成功');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
                }
                else{
                    echo "<script>alert('注册失败');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
                }
            }

            mysqli_close($conn);
        }
        else{
            echo "<script>alert('两次密码不一致');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
        }
    }
}else{
    echo "<script>alert('数据未成功提交');location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
    //header("Location: register.php");
}
